﻿using System;
using System.Data;
using System.Text;
using BO.Infrastructure.StaticData;
using BO.Infrastructure.Utils;
using BO.News;
using GUI.Extensions;
using ChannelVN.Cached;

namespace GUI.Controls.News
{
    public partial class BoxNews : System.Web.UI.UserControl
    {
        public int ZoneId { get; set; }
        public bool GetDataFromNoCacheLayer = false;
        private const string LiFormat = "<li>{3}<p><a title=\"{2}\" href=\"{0}\">{1}</a></p></li>";
        public int Top = 5;
        public string ZoneName { get; set; }
        public string Theme { get; set; }

        private const int ImageWidth = 100;
        private const int ImageHeight = 75;
        private const string LinkFormat = "<a href=\"{0}\">{1}</a>";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (ZoneId <= 0)
            {
                Visible = false;
                return;
            }
            var enableHtmlCaching = CacheSettingExtensions.EnableCacheHtml && GetDataFromNoCacheLayer;
            var isCachedUpdating = CacheController.IsCachedUpdating;

            var bo = enableHtmlCaching
                         ? NewsBO_NoCache.GetInstance()
                         : NewsBO.GetInstance();

            var dt = bo.GetNewsByPosition(
                top: Top,
                typeId: DefinedConstants.News.TypeIDs.TinTrangChuyenMuc,
                getDataFromMasterDataBase: isCachedUpdating);

            Visible = DataBind(dt);

            if (!Visible || !string.IsNullOrEmpty(ZoneName)) return;
            var zone = NewsBO.GetInstance().GetCategoryDetail(ZoneId);
            if (zone != null)
            {
                ZoneName = string.Format(LinkFormat, zone.Url, zone.Name);
                var zoneMetaData = NewsBO.GetInstance().GetCategoryMetaData(zone.ParentId > 0 ? zone.ParentId : zone.Id);

                if (zoneMetaData != null && string.IsNullOrEmpty(Theme))
                {
                    Theme = zoneMetaData.Theme;
                }
            }

        }

        private bool DataBind(DataTable dt)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                var sb = new StringBuilder();
                foreach (DataRow r in dt.Rows)
                {
                    var avatar = PresentationUtils.Photo.BuildNewsAvatar(r, ImageWidth, ImageHeight, lazyLoad: true);
                    sb.AppendFormat(LiFormat,
                                    r[SqlConstants.NewsPublish.Url],
                                    r[SqlConstants.NewsPublish.Title],
                                    PresentationUtils.EnCode(r[SqlConstants.NewsPublish.Title].ToString()),
                                    avatar);
                }
                ltrData.Text = sb.ToString();
                return true;
            }
            return false;
        }
    }
}